import config from "./config.js"


function getToken(){
    return new Promise((resolve,reject)=>{
        wx.getStorage({
            key: 'token',
            success: res=>{
               resolve(res.data)
            },
            fail:err=>{
                resolve("111")
            //    console.log(err)
            }
        
        })
    })
}


export  function request(url,method,data){
    // let token=await getToken()
   
    return new Promise((resolve,reject)=>{
       
        wx.showLoading({
            title:"加载中...",
            duration:600
        })
        getToken().then(token=>{
            wx.request({
                url: config.baseUrl + url,
                data: data||{},
                method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
                header: {
                    token:token||"111"
                }, // 设置请求的 header
                success: res=>{
                    // console.log(res.data)
                    if(res.data.head.status == 1){
                        resolve(res.data)
                    }else if(res.data.head.status == 0){
                        wx.showToast({
                            title: res.data.head.message,
                            icon: 'none',
                            duration:2000,
                        })
                        if(res.data.head.statusCode =="USR_003"){
                            reject(res.data.head.message)
                        }

                        if(res.data.head.statusCode =="USR_001"){
                            // wx.showModal({
                            //   cancelColor: 'cancelColor',
                            //   title:"账号异常"
                            // })
                            reject(res.data.head.message)
                        }
                        
                    }
                    // else if(res.data.head.statusCode =="USR_027"){
                    //     reject()
                    // }
                    else{
                        setTimeout(() => {
                            wx.reLaunch({
                              url: '/pages/index/index',
                            })
                        }, 1000);
                    }
              
                },
                fail: function() {
                    // fail
                    wx.showToast({
                        title: '网络错误',
                        icon: 'none',
                        duration:2000
                    })
                },
                complete:res=>{
                    // wx.hideLoading()

                }
            })
        })

       
    })

  
} 